######################################
# Django 模块
######################################
import random

from django.shortcuts import render, HttpResponseRedirect, redirect, reverse
from django.utils.encoding import escape_uri_path
from django.views import View
from django.http import HttpResponse, JsonResponse
from django.db.models import Q
from django.urls import reverse
import os

######################################
# 第三方模块
######################################
from pure_pagination import PageNotAnInteger, Paginator, EmptyPage

######################################
# 系统模块
######################################
import json
import datetime

######################################
# 自建模块
######################################
from utils.login_check import LoginStatusCheck
from users.models import UserProfile
from .forms import *
from .models import *

time_list={'试用':1,'周卡':7,'月卡':30,'永久':999}
cards_list={'试用':'testcard','周卡':'weekcard','月卡':'monthcard','永久':'foevercard'}

######################################
# 创建注册码
######################################
class TokenCreateView(LoginStatusCheck, View):
    def get(self, request):
        # 页面选择
        web_chose_left_1 = 'topnews'
        web_chose_left_2 = 'company'
        web_chose_middle = ''

        title = '创建注册码'
        versionstrings=Update.objects.filter(type='latest')
        version={}
        for i in versionstrings:
            version[i.chanel]=i.chanel_name
        context = {
            'web_chose_left_1': web_chose_left_1,
            'web_chose_left_2': web_chose_left_2,
            'web_chose_middle': web_chose_middle,
            'title': title,
            'version':version
            # {'A':'普通版','V':'代理版','J':'聚鑫头条','M':'墨诚阅读'}
        }
        return render(request, 'topnews/token_creat.html', context=context)


######################################
# 订单统计
######################################
class OrderListView(LoginStatusCheck, View):
    def get(self, request):
        # 页面选择
        web_chose_left_1 = 'topnews'
        web_chose_left_2 = 'ops'
        web_chose_middle = ''

        title = '订单统计'

        orders = OrderList.objects.filter(account_from=request.user.username)
        # 关键字
        keyword = request.GET.get('keyword', '')
        if keyword != '':
            orders = orders.filter(
                Q(Cards_type__icontains=keyword) | Q(Cards_Count__icontains=keyword) | Q(Money__icontains=keyword)| Q(name=keyword))

        orders_nums = orders.count()
        # 判断页码
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 对取到的数据进行分页，记得定义每页的数量
        p = Paginator(orders, 8, request=request)
        # 分页处理后的 QuerySet
        orders = p.page(page)

        context = {
            'web_chose_left_1': web_chose_left_1,
            'web_chose_left_2': web_chose_left_2,
            'web_chose_middle': web_chose_middle,
            'title': title,
            'orders': orders,
            'orders_nums': orders_nums,
        }
        return render(request, 'topnews/orderlist.html', context=context)

######################################
# 订单删除
######################################
class OrderLisDeletetView(LoginStatusCheck, View):
    def post(self, request):
        order_id = request.POST['order_id']
        if request.user.role>1:
            order = OrderList.objects.filter(order_id=order_id)
            if order:
                order.delete()
                context = {'status':'success','message': '成功删除订单及包含的所有注册码！'}
            else:
                context={'message': '不存在此订单'}
        else:
            context={'message': '对不起，你没有足够的权限删除订单！'}
        return JsonResponse(context)


######################################
# 注册卡管理
######################################
class TokenListView(LoginStatusCheck, View):
    def get(self, request):
        # 页面选择
        web_chose_left_1 = 'topnews'
        web_chose_left_2 = 'other'
        web_chose_middle = ''

        title = '注册卡管理'
        tokens = Customer.objects.filter(author=request.user.username)
        # 关键字
        keyword = request.GET.get('keyword', '')
        if keyword != '':
            tokens = tokens.filter(
                Q(token__icontains=keyword) | Q(name__icontains=keyword) | Q(title__icontains=keyword))

        # 数量
        tokens_nums = tokens.count()

        # 判断页码
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        # 对取到的数据进行分页，记得定义每页的数量
        p = Paginator(tokens, 8, request=request)
        # 分页处理后的 QuerySet
        tokens = p.page(page)
        context = {
            'web_chose_left_1': web_chose_left_1,
            'web_chose_left_2': web_chose_left_2,
            'web_chose_middle': web_chose_middle,
            'title': title,
            'platforms': tokens,
            'platform_nums': tokens_nums,
        }
        return render(request, 'topnews/token_manager.html', context=context)


######################################
# 固定注册码创建
######################################
class TokenCreateOneView(LoginStatusCheck, View):
    def post(self, request):
        add_token_form = SingleTokenForm(request.POST)
        if add_token_form.is_valid():
            version = request.POST.get('version')
            type = request.POST.get('type')
            token = request.POST.get('token')
            name = request.POST.get('name')
            money = request.POST.get('money')
            token = version + token
            person = request.user
            if version in person.versionstring:
                cards = getattr(person, cards_list[type])
                if not Customer.objects.filter(token=token):
                    if cards > 0:
                        try:
                            setattr(person, cards_list[type], cards - 1)
                            person.save()
                            order_id=datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                            Order = OrderList(account_from=person.username, Cards_type=type, Cards_Count=1, Money=money, name=name,order_id=order_id)
                            Order.save()
                            order=OrderList.objects.get(order_id=order_id)
                            add = Customer(token=token, name=name, author=person.username, title=type,order_id=order)
                            add.save()
                            context = {'message': '添加成功，您的注册码为' + token}
                        except:
                            context = {'message': '添加失败'}
                    else:
                        context = {'message': '对不起，您没有足够的配额，请找管理员充值！'}
                else:
                    context = {'message': '此注册码已存在'}
            else:
                context = {'message': '对不起，您没有权限创建此类注册码，请联系管理员！'}
        else:
            context = {'message': '填写的内容不符合格式，请检查！'}
        return JsonResponse(context)

######################################
# 随机注册码创建
######################################
class TokenCreateMoreView(LoginStatusCheck, View):
    def post(self, request):
        add_token_form = IndexTokenForm(request.POST)
        if add_token_form.is_valid():
            version = request.POST.get('version')
            type = request.POST.get('type')
            count = int(request.POST['count'])
            name = request.POST.get('name')
            person = request.user
            money = int(request.POST['money'])
            if version in person.versionstring:
                cards = getattr(person, cards_list[type])
                token_list = []
                num = count
                if cards >= abs(count)&count!=0:
                    setattr(person, cards_list[type], cards - abs(count))
                    person.save()
                    order_id=datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                    Order = OrderList(account_from=person.username, Cards_type=type, Cards_Count=num, Money=money, name=name,order_id=order_id)
                    Order.save()
                    order=OrderList.objects.get(order_id=order_id)
                    while (count > 0):
                        s = version
                        for j in range(10):
                            x = random.randint(0, 9)
                            s = s + str(x)
                        list = Customer.objects.filter(token=s)
                        if not list:
                            add = Customer(token=s, name=name, author=person.username, title=type,order_id=order)
                            add.save()
                            token_list.append(s)
                            count -= 1
                    token_list.reverse()
                    context = {'status':'success','list': token_list, 'title': type, 'num': num}
                else:
                    context = {'user': '对不起，', 'message': '您没有足够的配额，请找管理员充值！'}
            else:
                context = {'user': '对不起，', 'message': '您没有权限创建此类注册码，请联系管理员！'}
        else:
            context = {'message': '填写的内容不符合格式，请检查！'}
        return JsonResponse(context)

######################################
# 自定义注册码创建
######################################
class TokenCreateIndexView(LoginStatusCheck, View):
    def post(self, request):
        add_token_form = DiyTokenForm(request.POST)
        if add_token_form.is_valid():
            version = request.POST.get('version')
            type = request.POST.get('type')
            diycode = request.POST['diycode']
            count = int(request.POST['count'])
            name = request.POST.get('name')
            person = request.user
            money = int(request.POST['money'])
            if version in person.versionstring:
                cards = getattr(person, cards_list[type])
                token_list = []
                count = abs(count)
                num = count
                if cards >= count&count!=0:
                    setattr(person, cards_list[type], cards - count)
                    person.save()
                    setattr(person, cards_list[type], cards - abs(count))
                    person.save()
                    order_id=datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                    Order = OrderList(account_from=person.username, Cards_type=type, Cards_Count=num, Money=money, name=name,order_id=order_id)
                    Order.save()
                    order=OrderList.objects.get(order_id=order_id)
                    index=1
                    while (count > 0):
                        s = version+diycode
                        x = str(index)
                        s = s + str(x)
                        list = Customer.objects.filter(token=s)
                        if not list:
                            add = Customer(token=s, name=name, author=person.username, title=type,order_id=order)
                            add.save()
                            token_list.append(s)
                            count -= 1
                        index+=1
                    token_list.reverse()
                    context = {'status':'success','list': token_list, 'title': type, 'num': num}
                else:
                    context = {'user': '对不起，', 'message': '您没有足够的配额，请找管理员充值！'}
            else:
                context = {'user': '对不起，', 'message': '您没有权限创建此类注册码，请联系管理员！'}
        else:
            context = {'message': '填写的内容不符合格式，请检查！'}
        return JsonResponse(context)


######################################
# 配额转让
######################################
class TokenTransferView(LoginStatusCheck, View):
    def post(self, request):
        token_transfer_form = TokenTransferForm(request.POST)
        if token_transfer_form.is_valid():
            type = request.POST.get('type')
            count = abs(int(request.POST['count']))
            name = request.POST.get('name')
            username=request.POST.get('username')
            person = request.user
            money = int(request.POST['money'])
            cards = getattr(person, cards_list[type])
            if cards >= count:
                toperson = UserProfile.objects.filter(username=username)
                if toperson:
                    toperson=toperson[0]
                    tocards = getattr(toperson, cards_list[type])
                    setattr(person, cards_list[type], cards-count)
                    setattr(toperson, cards_list[type], tocards+count)
                    person.save()
                    toperson.save()
                    order_id=datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                    Order = OrderList(account_from=person.username, Cards_type=type, Cards_Count=count, Money=money, name=name,order_id=order_id)
                    Order.save()
                    context = {'message': '转让成功'}
                else:
                    context = {'message': '未查询到此用户，请核对目标用户账号！'}
            else:
                context = {'message': '您没有足够的配额，请找管理员充值！'}
        else:
            context = {'message': '填写的内容不符合格式，请检查！'}
        return JsonResponse(context)



######################################
#口令获取
######################################
class courseView(View):
    def get(self, request):
        return render(request, 'topnews/course.html')

######################################
#注册码绑定
######################################
class TokenRegisterView(View):
    def post(self, request):
        token = request.POST['token']
        id = request.POST['id']
        list = Customer.objects.filter(token=token)
        if list:
            if list[0].number == '':
                list[0].number = id
                list[0].register_count += 1
                list[0].register_time = datetime.datetime.now()
                if(list[0].Duty_time is None):
                    list[0].Duty_time = datetime.datetime.now() + datetime.timedelta(days=time_list[list[0].title])
                list[0].save()
                context = {'resultcode': 200, 'data1': token, 'data2': id,'message': '可以开始运行啦'}
            elif list[0].number == id:
                context = {'resultcode': 100, 'data1': token, 'data2': id, 'message': '已经注册过啦，直接运行吧'}
            else:
                context = {'resultcode': 100, 'data1': token, 'data2': id, 'message': '此注册码未绑定此手机'}
        else:
            context = {'resultcode': 100, 'data1': token, 'data2': id, 'message': '此注册码不存在'}
        return JsonResponse(context)

######################################
#注册码认证
######################################
class TokenIdentificationView(View):
    def post(self, request):
        context ={}
        token = request.POST['token']
        id = request.POST['id']
        list = Customer.objects.filter(token=token)
        update = Update.objects.filter(type='latest')
        context ={}
        context['version'] = update[0].version
        context['data1'] =token
        context['data2'] =id
        if list:
            if list[0].number == id:
                i = list[0]
                thetime=str(i.Duty_time)[:19]
                dutytime=datetime.datetime.strptime(thetime,'%Y-%m-%d %H:%M:%S')
                if (dutytime-datetime.datetime.now()).days>=0:
                    context['token'] = i.token
                    context['name'] = i.name
                    context['number'] = i.number
                    context['title'] = i.title
                    context['time'] = thetime
                    i.run_count += 1
                    i.last_run_time = datetime.datetime.now()
                    i.save()
                    context['resultcode'] = 200
                    context['message'] = '恭喜发财！'
                else:
                    context['resultcode'] = 100
                    context['message'] ='此注册码已过期'
            else:
                context['resultcode'] = 100
                context['message'] = '此注册码未绑定此手机'
        else:
            context['resultcode'] = 100
            context['message'] ='此注册码不存在'
        return JsonResponse(context)


######################################
#注册码解绑
######################################
class TokenCancelNormalView(View):
    def post(self, request):
        token = request.POST['token']
        id = request.POST['id']
        list = Customer.objects.filter(token=token)
        if list:
            if list[0].number == id:
                list[0].number = ''
                list[0].cancel_time = datetime.datetime.now()
                list[0].save()
                context = {'resultcode': 200, 'data1': token, 'data2': id, 'message': '可以在其他手机上绑定啦'}
            else:
                context = {'resultcode': 100, 'data1': token, 'data2': id, 'message': '此注册码不属于本手机'}
        else:
            context = {'resultcode': 100, 'data1': token, 'data2': id, 'message': '此注册码不存在'}
        return JsonResponse(context)


######################################
#更新检测
######################################
class UpdataStatusView(View):
    def get(self, request):
        try:
            chanel = request.GET.get('chanel','A')
        except:
            chanel='A'
        context = {}
        list = Update.objects.filter(type='latest').filter(chanel=chanel)
        if list:
            context['version'] = list[0].version
            context['type'] = list[0].type
            context['force'] = list[0].force
            context['detial'] = list[0].detial
        return JsonResponse(context)
    def post(self, request):
        context = {}
        list = Update.objects.filter(type='latest')
        if list:
            context['version'] = list[0].version
            context['type'] = list[0].type
            context['force'] = list[0].force
            context['detial'] = list[0].detial
        return JsonResponse(context)



######################################
# 续费注册码
######################################
class TokenAddTimeView(LoginStatusCheck, View):
    def post(self, request):
        add_token_time_form = TokenAddTimeForm(request.POST)
        if add_token_time_form.is_valid():
            token = request.POST['token']
            type = request.POST['type']
            user = request.session.get('user', 'False')
            person = request.user
            list = Customer.objects.filter(token=token)
            cards = getattr(person, cards_list[type])
            if list:
                if cards > 0:
                    setattr(person, cards_list[type], cards - 1)
                    person.save()
                    list[0].Duty_time += datetime.timedelta(days=time_list[type])
                    try:
                        list[0].save()
                        order_id=datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                        Order = OrderList(account_from=user, account_to='续费', Cards_type=type,Cards_Count=1,order_id=order_id)
                        Order.save()
                        context = {'status':'success','message': '续费成功'}
                    except:
                        context = {'message': '续费失败'}
                else:
                    context = {'message': '对不起，您没有足够的配额，请找管理员充值！'}
            else:
                context = {'message': '此注册码不存在'}
        return JsonResponse(context)




######################################
# 解绑注册码
######################################
class TokenCancelAdminView(LoginStatusCheck, View):
    def post(self, request):
        token = request.POST['token']
        list = Customer.objects.filter(token=token)
        if list:
            if request.user.role>1:
                list[0].number= ''
                list[0].save()
                context = {'status':'success','message': '解绑成功'}
            else:
                context = {'message': '无权限解绑注册码'}
        else:
            context={'message': '此注册码不存在'}
        return JsonResponse(context)


######################################
#根据参数下载
######################################
class DownloadApkView(View):
    def get(self, request):
        chanel = request.GET.get('chanel','A')
        file = open('static/upload/'+chanel+'.apk', 'rb')
        response = HttpResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        version = Update.objects.filter(type='latest').filter(chanel=chanel)[0]
        response['Content-Disposition'] = "attachment;filename*=utf-8''{}".format(
            escape_uri_path(version.chanel_name + version.version + '.apk'))
        return response
######################################
#更新信息
######################################
class UpdateInfoView(View):
    def post(self, request):
        version = request.POST['version']
        force = request.POST['force']
        detial = request.POST['detial']
        chanel = request.POST['chanel']
        info = Update.objects.filter(chanel=chanel).filter(type='latest')[0]
        info.version=version
        info.detial=detial
        info.force=(force=='true')
        info.Create_Time=datetime.datetime.now()
        info.save()
        return JsonResponse({'message': '更新成功'})

######################################
#添加渠道
######################################
class AddChanelView(View):
    def post(self, request):
        chanel_name = request.POST['chanel_name']
        chanel = request.POST['chanel']
        info = Update(chanel=chanel,chanel_name=chanel_name,version='1',type='latest')
        info.save()
        return JsonResponse({'status': 'success'})

######################################
#根据参数上传
######################################
class UploadApkView(View):
    def post(self, request):
        chanel = request.POST['chanel']
        path = 'static/upload/'
        handle_upload_file(request.FILES['file'], chanel+'.apk', path)
        return JsonResponse({'message': '上传成功'})


def handle_upload_file(file, filename,path):
    if not os.path.exists(path):
        os.makedirs(path)
    with open(path + filename, 'wb+')as destination:
        for chunk in file.chunks():
            destination.write(chunk)















